package com.dingpeikeji.quickdeer.utils;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.sun.xml.internal.bind.v2.runtime.unmarshaller.LocatorEx.Snapshot;

public class OrderUtil
{
	private static final String RSA2_PRIVATE = "MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQC7HXKsaKd59gqus4B2NE35t1duC5BEs1CT/1rsh/ozrEcdb/m4hrN83MB6GXwJ191456qtSdyBNcoLKgDuCV09qyyEQaCsNKOgbDIdR3ZFp02YjuwYFDpdq0ub/Y6F988DaJ89hMso58mwuNIW0st9R47qLKFyEp89Q0mE7GO1RikQfujhUrNvCmBpnSSg/N6utOsA/FcuQbIPdIpDYJaxk/RzO/vHkBo1vWNgYsJLWiTgV+pM/JNLv6va6algYInYiTs8IqPrXRpmwMXdtQ19V4Wc2bVn4P9fMxKxCH5C2Tn8H06AW0GzJvMdPd7Oabr7Z/oBdbszWqSSdHvGiMLDAgMBAAECggEACdvSV+0nrdBd3biNcyzsUtTrIVwwnL4J59JTexTrBN/120I0GRnXySNkbMp885PREna6UmkK2i/4VkA/TktmA0LKlKlUit43JNOujEZgn+jhuMEHBXnDXX4R/MUORla5LIfNpBMkFSKpSMtkHlm66P3lNMdnNjhu9W5fKEbANiPGHDJYkbY7UuwQJLlaOGKpF3piPi0H8/jk9aQv9djDowNF1uXf1D6l+ObHxcest27yasHpg1JblmZdGVF8ATWI1MOJPF9kEaCe7RDld2fZTLc486Ke1FeS3NHHqdSoITSVGSZ+Fpiup+9WnDTRhXo/Y1v6/WUkUxuneGdEYhVmqQKBgQDmWJScG2fmZ134jVyj+0/U8XoN+s5hCaijppEqtZPBdh3A75PmGbyUfHwWUNAZKoCMQR6F2SUYX7uKOSDs/fdrPsKss+8Vgz6nnwCwq7N0QTJHZ6OztNvErbndjsOg13X2EkbpZAUcAFOIiLrPU7DDMnDPvGP6veLU3cNxUtAk3QKBgQDP9E3imkOwspulQ0SCmB4QU8UT/kzxGe7p5NY0xgR5nRvWYj3KWHUgx833Pbpcrv+Q7vkFKtMv1nIKrDHEHhbSqStPmGQoigXxD62COwcbTlhGX6ZdtTb2Aw1f3dDEXvQu87xtVV2wz4SRF3uXuU//c07rTGY3W75ZJ3oxuCq8HwKBgCXO4k2hPfOWgdkbMtqDlH3qSNNkmF1bHYAHBgrRlPgLMCUL7eW10bs5l5B+IToQPNtIkP79PlZ62Ch+6gWcRfEncwKv4g1Q5obS1WUqOaFaVitcOoVzqSLmNPzFwxxyYR1LsLH8Rc5ry0o8zxTassfHTrb6QBrW8hVodPzzz9BNAoGADdwqlL/TYyOEXC9vkYSx/ESZDgwU9LzVv6EQ5dOM2M4v3MoPdD0REW4/vArRMPw47GABGOcRzE5uq2duqbOXsdK0oEl343vPiZGR7uwgPSGroIUfgX9iemMZsRoHoA70F20HUgIujGpIW6NFCYfAXTZCPEyLQ4VJ2odXDZlIv+ECgYEArnqEzlnWAs/S2n1Col4C32r4WIZOVXA29r08jK5cVvxugY0uLC6eKuXUOJaTU8GYJ7ASG5wHbtYcx+Vq6FECfIq7gBpkayz5oOeatoIsyYvHTh8KMComzfXHry3NmRuMBTXL1m5xK6crgQIiCFiMwwkLZ9y/Npp2K/aHjYzUo+Q=";

    /**
     * 构造授权参数列表
     *
     * @param pid
     * @param app_id
     * @param target_id
     * @return
     */
    public static Map<String, String> buildAuthInfoMap(String pid, String app_id, String target_id, boolean rsa2)
    {
        Map<String, String> keyValues = new HashMap<String, String>();

        // 商户签约拿到的app_id，如：2013081700024223
        keyValues.put("app_id", app_id);

        // 商户签约拿到的pid，如：2088102123816631
        keyValues.put("pid", pid);

        // 服务接口名称， 固定值
        keyValues.put("apiname", "com.alipay.account.auth");

        // 商户类型标识， 固定值
        keyValues.put("app_name", "mc");

        // 业务类型， 固定值
        keyValues.put("biz_type", "openservice");

        // 产品码， 固定值
        keyValues.put("product_id", "APP_FAST_LOGIN");

        // 授权范围， 固定值
        keyValues.put("scope", "kuaijie");

        // 商户唯一标识，如：kkkkk091125
        keyValues.put("target_id", target_id);

        // 授权类型， 固定值
        keyValues.put("auth_type", "AUTHACCOUNT");

        // 签名类型
        keyValues.put("sign_type", rsa2 ? "RSA2" : "RSA");

        return keyValues;
    }

    /**
     * 构造支付订单参数列表
     *
     */
    public static Map<String, String> buildOrderParamMap(String app_id, boolean rsa2, String tradeNo, String subject, String body, String price)
    {
        
        Map<String, String> keyValues = new TreeMap<String, String>();

        keyValues.put("app_id", app_id);

        keyValues.put("method", "alipay.trade.app.pay");
        
        keyValues.put("charset", "utf-8");
        
        keyValues.put("sign_type", "RSA2");
        
        SimpleDateFormat format =  new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        keyValues.put("timestamp",format.format(new Date()));
        
        keyValues.put("version", "1.0");
        
        keyValues.put("notify_url", "https://www.xiakeyueche.com/alipay/notify");
        
        keyValues.put("biz_content", "{\"timeout_express\":\"30m\",\"product_code\":\"QUICK_MSECURITY_PAY\",\"total_amount\":\"" + price + "\",\"subject\":\"" + subject + "\",\"body\":\"" + body + "\",\"out_trade_no\":\"" + tradeNo + "\"}");

        return keyValues;
    }

    /**
     * 构造支付订单参数信息
     *
     * @param map 支付订单参数
     * @return
     */
    public static String buildOrderParam(Map<String, String> map)
    {
        ArrayList<String> list = new ArrayList<String>();
		for (Map.Entry<String, String> entry : map.entrySet()) {
			if (entry.getValue() != "") {
				list.add(entry.getKey() + "=" + entry.getValue() + "&");
			}
		}
		int size = list.size();
		String[] arrayToSort = list.toArray(new String[size]);
		Arrays.sort(arrayToSort, String.CASE_INSENSITIVE_ORDER);
		StringBuilder sb = new StringBuilder();
		for (int i = 0; i < size; i++) {
			sb.append(arrayToSort[i]);
		}
		String result = sb.toString();
		result = result.substring(0,result.length()-1);
		return result;
    }

    /**
     * 拼接键值对
     *
     * @param key
     * @param value
     * @param isEncode
     * @return
     */
    private static String buildKeyValue(String key, String value, boolean isEncode)
    {
    	isEncode = true;
        StringBuilder sb = new StringBuilder();
        sb.append(key);
        sb.append("=");
        if (isEncode)
        {
            try
            {
                sb.append(URLEncoder.encode(value, "UTF-8"));
            }
            catch (UnsupportedEncodingException e)
            {
                sb.append(value);
            }
        } else
        {
            sb.append(value);
        }
        return sb.toString();
    }

    /**
     * 对支付参数信息进行签名
     *
     * @param map 待签名授权信息
     * @return
     * @throws AlipayApiException 
     * @throws UnsupportedEncodingException 
     */
    public static String getSign(String orderParam, String rsaKey, boolean rsa2) throws AlipayApiException, UnsupportedEncodingException{
    	//String oriSign = SignUtils.sign(orderParam, rsaKey, rsa2);
        String rsaSign = AlipaySignature.rsaSign(orderParam,OrderUtil.RSA2_PRIVATE,"utf-8", "RSA2");
        String result = orderParam;
        //遇到'&'分隔
        String[] arr = result.split("&");
        Map<String, String> map = new TreeMap<String, String>();
        for (String str : arr) {
        	String[] sub = str.split("=");
        	map.put(sub[0], sub[1]);
        }
        //不让"="编码
        Map<String, String> encodeMap = new TreeMap<String, String>();
        for (Map.Entry<String,String> en : map.entrySet()) {
        	String value = en.getValue();
        	value  = URLEncoder.encode(value, "utf-8");
        	encodeMap.put(en.getKey(), value);
		}
        //拼接编码后的结果
        StringBuilder sb = new StringBuilder();
        for (Map.Entry<String,String> en : encodeMap.entrySet()) {
        	sb.append(en.getKey()).append("=").append(en.getValue()).append("&");
		}
        //最后拼接sign
        String signEncode = URLEncoder.encode(rsaSign, "utf-8");
        sb.append("sign=").append(signEncode);
        return sb.toString();
    }
}
